package com.wutong.authority_server.filter;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wutong.authority_server.entity.User;
import com.wutong.authority_server.mapper.UserMapper;
import com.wutong.authority_server.service.UserService;
import com.wutong.authority_server.service.impl.UserDetailsServiceImpl;
import com.wutong.authority_server.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//用户登录成功后带上token验证过滤器
public class TokenAuthFilter extends BasicAuthenticationFilter {


    private RedisTemplate redisTemplate;
   private UserService userService;

    public TokenAuthFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate, UserService userService) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        //判断如果有权限信息，放到权限上下文中
        if(authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header获取token
        String token = request.getHeader("Authorization");
        if(token != null) {
            //从token获取用户名
            String username = TokenUtil.getUsername(token);
            //获取用户权限信息
            User user = userService.selectByUsername(username);
            List<GrantedAuthority> userAuthorityInfo = userService.getUserAuthorityInfo(user.getUserId());
            return new UsernamePasswordAuthenticationToken(username,token,userAuthorityInfo);
        }

        return null;
    }

}
